import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';

import '../../../hj_model/acg/comic_chapters_model.dart';
import '../../../hj_model/cartoon_media_info.dart';
import '../../../hj_utils/api_service/acg_service.dart';
import '../../live/live_widget.dart';

class CartoonEpisodeMenuAlert extends StatefulWidget {
  final ComicChapterInfo? curModel;
  final CartoonMediaInfo? cartoonModel;
  final Function(ComicChapterInfo)? callback;

  CartoonEpisodeMenuAlert(this.curModel, {this.callback, this.cartoonModel});

  @override
  State<StatefulWidget> createState() {
    return _CartoonEpisodeMenuAlertState();
  }
}

class _CartoonEpisodeMenuAlertState extends State<CartoonEpisodeMenuAlert> {
  CartoonMediaInfo? get cartoonModel => widget.cartoonModel;
  RefreshController? refreshController;

  @override
  void initState() {
    super.initState();
    if (cartoonModel?.haxNextEpisode == false) {
      //  refreshController?.loadNoData();
    }
  }

  bool _isLoading = false;
  bool _isReloading = false;

  void _loadMoreData({bool isSortExchange = false}) async {
    try {
      if (_isLoading) return;
      _isLoading = true;
      int currentPage = cartoonModel?.episodeCurPage ?? 0;
      if (isSortExchange) {
        _isReloading = true;
        currentPage = 0;
        if (cartoonModel?.isUpSort == 1) {
          cartoonModel?.isUpSort = 0;
        } else {
          cartoonModel?.isUpSort = 1;
        }
        setState(() {});
      }
      final episodeModel = await ACGService.mediaContentChapterList(
        cartoonModel?.id ?? "",
        currentPage + 1,
        cartoonModel?.episodePageSize ?? 20,
        sortType: cartoonModel?.isUpSort,
      );
      if ((currentPage + 1) == 1) {
        cartoonModel?.episodeList = episodeModel?.list;
      } else {
        cartoonModel?.episodeList?.addAll(episodeModel?.list ?? []);
      }
      cartoonModel?.episodeCurPage = currentPage + 1;
      cartoonModel?.haxNextEpisode = episodeModel?.hasNext ?? true;
      setState(() {});
    } catch (e) {
      debugLog(e);
    }
    _isLoading = false;
    _isReloading = false;
    if (cartoonModel?.haxNextEpisode == true) {
      refreshController?.loadComplete();
    } else {
      refreshController?.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Container(
        padding: EdgeInsets.fromLTRB(18.w, 21, 18.w, 32),
        height: 460,
        decoration: BoxDecoration(borderRadius: BorderRadius.vertical(top: Radius.circular(18)), color: Color(0xff171921)),
        child: Column(
          // crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              decoration: BoxDecoration(color: Colors.white.withOpacity(.3), borderRadius: BorderRadius.circular(4)),
              width: 38,
              height: 3,
            ),
            18.h.sizeBoxH,
            Row(
              children: [
                Text(
                  "剧集列表",
                  style: TextStyle(
                    fontSize: 16,
                    color:  Color(0x8CFFFFFF),
                  ),
                ),
                const Spacer(),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    InkWell(
                      onTap: () {
                        _loadMoreData(isSortExchange: true);
                      },
                      child: Text(
                        "升序",
                        style: TextStyle(
                          fontSize: 14,
                          color: cartoonModel?.isUpSort == 0 ? Color(0xffFD2D55) : Color(0x8CFFFFFF),
                        ),
                      ),
                    ),
                    2.sizeBoxW,
                    Text(
                      "/",
                      style: TextStyle(
                        fontSize: 14,
                        color: Color(0x8CFFFFFF),
                      ),
                    ),
                    2.sizeBoxW,
                    InkWell(
                      onTap: () {
                        _loadMoreData(isSortExchange: true);
                      },
                      child: Text(
                        "降序",
                        style: TextStyle(
                          fontSize: 14,
                          color: cartoonModel?.isUpSort != 0 ? Color(0xffFD2D55) : Color(0x8CFFFFFF),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            18.h.sizeBoxH,
            if (_isReloading)
              LoadingCenterWidget()
            else
              Expanded(
                child: pullYsRefresh(
                  // refreshController: refreshController,
                  onInit: (ctr) => refreshController = ctr,
                  enablePullDown: false,
                  onLoading: (refreshController) => _loadMoreData(),
                  noDataText: "",
                  child: GridView.builder(
                    padding: EdgeInsets.zero,
                    itemCount: cartoonModel?.episodeList?.length ?? 0,
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 6,
                      crossAxisSpacing: 8,
                      mainAxisSpacing: 12,
                      childAspectRatio: 1,
                    ),
                    itemBuilder: (context, index) {
                      ComicChapterInfo model = cartoonModel!.episodeList![index];
                      bool isSelected = model.id == widget.curModel?.id;
                      return GestureDetector(
                        onTap: () {
                          if (!isSelected) {
                            widget.callback?.call(model);
                            Get.back();
                          }
                        },
                        child: CartoonChapterItem(
                          model,
                          isSelected: isSelected,
                          isFirst: index == 0,
                          fatherM: cartoonModel!,
                        ),
                      );
                    },
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

class CartoonChapterItem extends StatelessWidget {
  final ComicChapterInfo model;
  final CartoonMediaInfo fatherM;
  final bool isSelected;
  final bool isFirst;
  final bool canPlay;

  const CartoonChapterItem(this.model,
      {super.key, this.isSelected = false, this.canPlay = true, this.isFirst = false, required this.fatherM});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: isSelected ? Color(0x1A6975FF) : Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: isSelected ? Color(0xffFD2D55) : Color(0x1AFFFFFF), width: 1),
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            padding: EdgeInsets.only(top: 6),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "${model.episodeNumber}",
                  style: TextStyle(
                    color: isSelected ? Color(0xffFD2D55) : Color(0xE5FFFFFF),
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                if (isSelected && canPlay) ...[
                  2.sizeBoxW,
                  AudioWaveView(
                    color: Color(0xffFD2D55),
                    height: 10,
                  ),
                  // Image.asset(
                  //   'playing.png'.videoPath,
                  //   width: 20.w,
                  // )
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPriceItem() {
    int permission = model.listenPermission ?? 0;
    if (permission == 1 || fatherM.mediaStatus?.hasPaid == true) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(7),
            bottomRight: Radius.circular(7),
          ),
          gradient: LinearGradient(
            colors: [
              Color(0xff3E64EA),
              Color(0xff3E64EA),
            ],
          ),
        ),
        child: model.hasBuy == true || fatherM.mediaStatus?.hasPaid == true
            ? Text(
                "已解锁",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10,
                ),
              )
            : Row(
                children: [
                  Image.asset("coin.webp".commonImgPath, width: 10, height: 10),
                  Text(
                    "${model.price}",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 10,
                    ),
                  ),
                ],
              ),
      );
    }
    return SizedBox();
    // else if (permission == 2) {
    //   return Container(
    //     padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
    //     decoration: BoxDecoration(
    //       borderRadius: BorderRadius.only(
    //         topLeft: Radius.circular(7),
    //         bottomRight: Radius.circular(7),
    //       ),
    //       gradient: LinearGradient(
    //         colors: [
    //           Color(0xff3E64EA),
    //           Color(0xff3E64EA),
    //         ],
    //       ),
    //     ),
    //     child: Text(
    //       "免费",
    //       style: TextStyle(
    //         color: Colors.white,
    //         fontSize: 10,
    //       ),
    //     ),
    //   );
    // }  else {
    //   return Container(
    //     padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
    //     decoration: BoxDecoration(
    //       borderRadius: BorderRadius.only(
    //         topLeft: Radius.circular(7),
    //         bottomRight: Radius.circular(7),
    //       ),
    //       gradient: LinearGradient(
    //         colors: [
    //           Color(0xff3E64EA),
    //           Color(0xff3E64EA),
    //         ],
    //       ),
    //     ),
    //     child: Text(
    //       "VIP",
    //       style: TextStyle(
    //         color: Colors.white,
    //         fontSize: 10,
    //       ),
    //     ),
    //   );
    // }
  }
}
